package structs

import "fmt"

type TreeNode struct {
	Value       int
	Left, Right *TreeNode
}

// Print 接收方法
func (n *TreeNode) Print() {
	fmt.Println(n.Value)
}
func (n *TreeNode) SetValue(value int) {
	n.Value = value
}

func (n *TreeNode) Traverse() {
	n.TraverseFunc(func(node *TreeNode) {
		node.Print()
	})
	fmt.Println()
}

func (n *TreeNode) TraverseFunc(f func(node *TreeNode)) {
	if n == nil {
		return
	}
	n.Left.TraverseFunc(f)
	f(n)
	n.Right.TraverseFunc(f)
}

func (n *TreeNode) TraverseWithChannel() chan *TreeNode {
	out := make(chan *TreeNode)
	go func() {
		n.TraverseFunc(func(node *TreeNode) {
			out <- node
		})
		close(out)
	}()

	return out
}

// 工厂方法
func CreateNode(value int) *TreeNode {
	return &TreeNode{Value: value}
}
